package com.fivefu.core.camera.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.camera.entity.DbMonitorCamera;
import com.fivefu.core.camera.entity.DbMonitorLabel;
import com.fivefu.core.camera.services.*;
import com.fivefu.core.camera.vo.response.LabelPageList;
import com.fivefu.core.camera.vo.response.ProPageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class MonitorLabelServiceImpl implements MonitorLabelService {
    @Autowired
    private MonitorCameraService monitorCameraService;

    @Autowired
    private DbMonitorCameraService dbMonitorCameraService;

    @Autowired
    private DbMonitorCameraLabelService dbMonitorCameraLabelService;

    @Autowired
    private DbMonitorLabelService dbMonitorLabelService;


    /**
     * 批量增加标签下探头
     * @param labelId 标签编号
     * @param cameraIds 探头编号集合
     * @param userid 操作用户编号
     */
    @Override
    public void saveBatchCameraLabel(Long labelId, String cameraIds, String userid){

        List<Long> ids = Arrays.stream(cameraIds.split(",")).map(id->Long.parseLong(id)).collect(Collectors.toList());
        List<String> codes = dbMonitorCameraService.queryCameraCodesByIds(ids);

        //查询标签下所有关联信息
        List<Long> labels = new ArrayList<>();
        labels.add(labelId);
        Set<String> codeSet = dbMonitorCameraLabelService.queryMonitorCameraByLabelIds(labels);

        for (String cameraCode : codes) {
            if (!codeSet.contains(cameraCode)){
                dbMonitorCameraLabelService.insertMonitorCameraLabel(cameraCode,labelId,userid);
                codeSet.add(cameraCode);
            }
        }

    }

    /**
     *
     * 通过id删除标签
     * @param labelId  标签id
     * @param userId  用户编号
     */
    @Override
    public Boolean delMonitorLabelById(Long labelId,String userId) {
        QueryWrapper<DbMonitorLabel> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("id",labelId);

        DbMonitorLabel label = new DbMonitorLabel();
        label.setUpdatedBy(userId);
        label.setUpdatedTime(LocalDateTime.now());
        label.setIsDelete(1);

        boolean flag = dbMonitorLabelService.update(label, wrapper);

        //删除标签下探头
        dbMonitorCameraLabelService.delMonitorCameraLabelByLabelId(labelId, null ,userId);
        return flag;
    }

    /**
     *
     * 查询标签下探头列表
     * @param page 页数
     * @param limit 数量
     * @param labelId 标签id
     * @param cameraCode 探头编号
     * @param cameraName 探头类型
     * @param cameraType 标签名称
     * @param cameraManufacturer 厂商
     * @param cameraAreaid 所属区域
     * @param cameraStatus 探头状态
     *
     */
    @Override
    public Page<ProPageList> queryLabelMonList(Integer page, Integer limit, Long labelId, String cameraCode, String cameraName, String cameraType, String cameraManufacturer, String cameraAreaid, String cameraStreetid, String cameraStatus, String onlineStatus) {
        Page<ProPageList> returnPage = new Page<>();

        //在该标签下的所有探头编号
        List<Long> labelIds = new ArrayList<Long>(){{add(labelId);}};
        Set<String> set = dbMonitorCameraLabelService.queryMonitorCameraByLabelIds(labelIds);
        List<String> inCodes = new ArrayList<>(set);  // 满足条件的探头编码

        if (inCodes != null && inCodes.size() == 0){
            //表示该标签下无探头，不进行下一步查询
            returnPage.setTotal(0L);
            return returnPage;
        }
        Page<DbMonitorCamera> dbMonitorCameraPage = dbMonitorCameraService.queryCameraList(cameraName, cameraCode, cameraType, cameraAreaid, cameraStreetid, cameraStatus, onlineStatus, cameraManufacturer, inCodes, null, page, limit);
        if (dbMonitorCameraPage != null && dbMonitorCameraPage.getSize() > 0){
            //包含探头编码
            List<DbMonitorCamera> records = dbMonitorCameraPage.getRecords();
            List<ProPageList> proPageLists = monitorCameraService.cameraListToPageList(records);

            returnPage.setTotal(dbMonitorCameraPage.getTotal());
            returnPage.setRecords(proPageLists);
        }
        return returnPage;
    }

    /**
     *探头增加标签探头列表（排除已增加的探头）
     * @param page 页数
     * @param limit 数量
     * @param labelId 标签id
     * @param cameraCode 探头编号
     * @param cameraName 探头类型
     * @param cameraType 标签名称
     * @param cameraManufacturer 厂商
     * @param cameraAreaid 所属区域
     * @param cameraStreetid 所属街道
     * @param cameraStatus 探头状态
     */
    @Override
    public Page<ProPageList> queryMonitorNotInLabel(Integer page, Integer limit, Long labelId, String cameraCode, String cameraName, String cameraType, String cameraManufacturer, String cameraAreaid, String cameraStreetid, String cameraStatus, String onlineStatus) {
        Page<ProPageList> returnPage = new Page<>();
        //不在改标签下的所有探头编号
        List<Long> labelIds = new ArrayList<>();
        labelIds.add(labelId);
        Set<String> set = dbMonitorCameraLabelService.queryMonitorCameraByLabelIds(labelIds);
        List<String> excludIds = new ArrayList<>(set);

        //符合条件的探头列表
        Page<DbMonitorCamera> dbMonitorCameraPage = dbMonitorCameraService.queryCameraList(cameraName, cameraCode, cameraType, cameraAreaid, cameraStreetid, cameraStatus, onlineStatus, cameraManufacturer, null, excludIds, page, limit);

        if (dbMonitorCameraPage != null && dbMonitorCameraPage.getSize() > 0){
            List<DbMonitorCamera> records = dbMonitorCameraPage.getRecords();
            List<ProPageList> proPageLists = monitorCameraService.cameraListToPageList(records);
            returnPage.setRecords(proPageLists);
            returnPage.setTotal(dbMonitorCameraPage.getTotal());
        }
        return returnPage;
    }

    /**
     *批量移除标签下的探头
     * @param id  标签id
     * @param cameraIds 探头编号集合
     * @param userId  用户编号
     */
    @Override
    public boolean delMulMonitor(Long id, String cameraIds,String userId) {
        List<Long> ids = Arrays.stream(cameraIds.split(",")).map(cameraId->Long.parseLong(cameraId)).collect(Collectors.toList());
        List<String> codes = dbMonitorCameraService.queryCameraCodesByIds(ids);
        dbMonitorCameraLabelService.delMonitorCameraLabelByLabelId(id,codes,userId);
        return true;
    }

    /**
     *
     * 分页查询标签列表
     * @param page 页数
     * @param limit 数量
     * @param labelName  标签名称
     */
    @Override
    public Page<LabelPageList> queryLabelListByLabelName(Integer page, Integer limit, String labelName) {
        Page<LabelPageList> returnPage = new Page<>();
        List<DbMonitorLabel> list = new ArrayList<>();
        QueryWrapper<DbMonitorLabel> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.orderByDesc("updated_time");

        if (StrUtils.isNotEmpty(labelName)){
            wrapper.like("label_name",labelName);
        }
        if (page != null && limit != null){
            IPage iPage = new Page<>(page,limit);
            iPage = dbMonitorLabelService.page(iPage,wrapper);
            list = iPage.getRecords();
            returnPage.setTotal(iPage.getTotal());
        }else {
            list = dbMonitorLabelService.list(wrapper);
            returnPage.setTotal(list.size());
        }

        List<LabelPageList> collect = list.stream().map(l -> {
            LabelPageList label = new LabelPageList();
            label.setId(l.getId());
            label.setLabelName(l.getLabelName());
            label.setEditable(l.getEditable());
            label.setNumber(dbMonitorCameraLabelService.queryMonInLabNum(l.getId()));
            return label;
        }).collect(Collectors.toList());

        returnPage.setRecords(collect);
        return returnPage;
    }
}
